GLOBAL.fs = require('fs');
GLOBAL.URL = require('url');
GLOBAL.path = require('path');
GLOBAL.svr = require('./node_modules/websockets/lib/websockets/websockets');
GLOBAL.config = require('./config.js');

//Main server class
function mainServer() {
  this.ws;
  this.mods = {};
  
  //Socket manager
  var websockman = require('./sys/websockman.js').websockman;
  this.websockman = new websockman();
  
  //db
  var db = require('./sys/db.js').db;
  this.db = new db();
  this.db.init();
  
  //dispatcher
  var dispatcher = require('./sys/dispatcher.js').dispatcher;
  this.dispatcher = new dispatcher();
  this.dispatcher.modLoad(config.mods_dir);
  
  
  this.init = function(){
    main.ws = svr.createServer(main.requestListener);
    console.log(config.ws_port);
    main.ws.on('connect', main.onconnect).listen(config.ws_port);
  };
  
  this.requestListener = function(req, res) {
    var url = URL.parse(req.url);
    var file = path.join(__dirname, url.pathname);
    if(!path.existsSync(file)) {
      res.statusCode = 404;
      return res.end('' + 404);
    }
    var read = fs.createReadStream(file);
    read.pipe(res);
  };
  
  this.onconnect = function(socket) {
    main.websockman.onConnect(socket);
  };
}

GLOBAL.main = new mainServer();
// Start server
main.init();